package top.jfunc.common.db.data;

import top.jfunc.common.utils.StrUtil;

/**
 * @author <a href="https://github.com/TAKETODAY">Harry Yang</a>
 * @since 1.0 2022/11/24 19:19
 */
public class MySqlPagingQueryProvider extends PagingQueryProvider {

  @Override
  public String generateFirstPageQuery(int pageSize) {
    return SqlPagingQueryUtils.generateLimitSqlQuery(
        this, false, buildLimitClause(pageSize));
  }

  @Override
  public String generateRemainingPagesQuery(int pageSize) {
    if (StrUtil.isNotBlank(getGroupClause())) {
      return SqlPagingQueryUtils.generateLimitGroupedSqlQuery(
          this, true, buildLimitClause(pageSize));
    }
    else {
      return SqlPagingQueryUtils.generateLimitSqlQuery(
          this, true, buildLimitClause(pageSize));
    }
  }

  private String buildLimitClause(int pageSize) {
    return "LIMIT " + pageSize;
  }

  @Override
  public String generateJumpToItemQuery(int itemIndex, int pageSize) {
    int page = itemIndex / pageSize;
    int offset = (page * pageSize) - 1;
    offset = Math.max(offset, 0);

    String limitClause = "LIMIT " + offset + ", 1";
    return SqlPagingQueryUtils.generateLimitJumpToQuery(this, limitClause);
  }

}
